package com.channel.temperature.collect.ui.activity

import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Typeface
import android.net.Uri
import android.nfc.FormatException
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.PersistableBundle
import android.os.StrictMode
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.CompoundButton
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import androidx.annotation.RequiresApi
import androidx.core.content.FileProvider
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.github.gzuliyujiang.wheelpicker.DatimePicker
import com.github.gzuliyujiang.wheelpicker.annotation.DateMode
import com.github.gzuliyujiang.wheelpicker.annotation.TimeMode
import com.github.gzuliyujiang.wheelpicker.entity.DateEntity
import com.github.gzuliyujiang.wheelpicker.entity.DatimeEntity
import com.github.gzuliyujiang.wheelpicker.entity.TimeEntity
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.highlight.Highlight
import com.github.mikephil.charting.listener.OnChartValueSelectedListener
import com.github.mikephil.charting.utils.ColorTemplate
import com.hjq.toast.ToastUtils
import com.itextpdf.io.image.ImageDataFactory
import com.itextpdf.kernel.colors.DeviceRgb
import com.itextpdf.kernel.font.PdfFont
import com.itextpdf.kernel.font.PdfFontFactory
import com.itextpdf.kernel.geom.PageSize
import com.itextpdf.kernel.pdf.PdfDocument
import com.itextpdf.kernel.pdf.PdfWriter
import com.itextpdf.layout.Document
import com.itextpdf.layout.borders.DottedBorder
import com.itextpdf.layout.element.Paragraph
import com.itextpdf.layout.element.Table
import com.itextpdf.layout.element.Text
import com.itextpdf.layout.property.TextAlignment
import com.kongzue.dialogx.dialogs.InputDialog
import com.kongzue.dialogx.dialogs.MessageDialog
import com.kongzue.dialogx.dialogs.WaitDialog
import com.kongzue.dialogx.interfaces.OnDialogButtonClickListener
import com.channel.temperature.collect.R
import com.channel.temperature.collect.app.base.BaseActivity
import com.channel.temperature.collect.app.dao.OfflineBase
import com.channel.temperature.collect.app.ext.initBack
import com.channel.temperature.collect.app.ext.mmkv
import com.channel.temperature.collect.app.util.ExcelUtil
import com.channel.temperature.collect.app.util.MyUtil
import com.channel.temperature.collect.app.widget.MyMarkerView
import com.channel.temperature.collect.data.annotation.ValueKey
import com.channel.temperature.collect.data.response.LineDataBean
import com.channel.temperature.collect.data.response.OfflineBean
import com.channel.temperature.collect.databinding.ActivityOfflineDataBinding
import com.channel.temperature.collect.ui.viewmodel.OfflineDataModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.hgj.mvvmhelper.base.MvvmHelper
import me.hgj.mvvmhelper.base.appContext
import me.hgj.mvvmhelper.ext.hideStatusBar
import me.hgj.mvvmhelper.ext.isLandscape
import me.hgj.mvvmhelper.ext.setOnclickNoRepeat
import java.io.BufferedReader
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.InputStreamReader
import java.util.*


class OfflineDataActivity : BaseActivity<OfflineDataModel, ActivityOfflineDataBinding>(),
    OnChartValueSelectedListener, OnSeekBarChangeListener {
    protected var tfLight: Typeface? = null
    lateinit var dialog: WaitDialog
    val colorIntList = mutableListOf<Int>(
        R.color.color0,
        R.color.color1,
        R.color.color2,
        R.color.color3,
        R.color.color4,
        R.color.color5,
        R.color.color6,
        R.color.color7,
        R.color.color8,
        R.color.color9,
        R.color.color10,
        R.color.color11
    )

    //    private val mTemperatureAdapter: TemperatureAdapter by lazy { TemperatureAdapter() }
    var listData = ArrayList<OfflineBean>()

    var maxLong: Long = 0
    var minLong: Long = 0

    var leftMaxValue = 200.0f
    var rightMaxValue = 120.0f
    var leftMinValue = -25.0f
    var rightMinValue = -10f
    var checkedCount = 0

    var roomSize = 0

    var deviceName = ""
    var dataMode = 0
    var filePath = ""


    var excelDeviceName = ""
    var excelTaskName = ""
    var excelTaskDec = ""
    var excelStartTime = ""
    var excelEndTime = ""


    @RequiresApi(Build.VERSION_CODES.N)
    override fun initView(savedInstanceState: Bundle?) {
        mBind.customToolbar?.initBack("设备离线数据") {
            finish()
        }
        mBind.customToolbar?.setRightDrawable(R.mipmap.icon_share)
//        mBind.listRecyclerView.grid(1).divider {
//            orientation = DividerOrientation.GRID
//            includeVisible = true
//            setDivider(1, true)
//            setColor(getColorExt(R.color.common_text_hint_color))
//        }.adapter = mTemperatureAdapter


//        mTemperatureAdapter.setNewInstance(
//            listData
//        )
//        mTemperatureAdapter.notifyDataSetChanged()
        dataMode = intent.getIntExtra("dataMode", 0)
        Log.e("测试", "测试测试测试测试  dataMode  " + dataMode)
        filePath = intent.getStringExtra("filePath").toString()

        deviceName = intent.getStringExtra("deviceName").toString()



        tfLight = Typeface.createFromAsset(
            MvvmHelper.app.applicationContext.assets, "OpenSans-Light.ttf"
        )

        mBind.chart.setOnChartValueSelectedListener(this)

        // create marker to display box when values are selected
        val mv = MyMarkerView(
            MvvmHelper.app.applicationContext, R.layout.custom_marker_view
        )

        // Set the marker to the chart

        // Set the marker to the chart
        mv.setChartView(mBind.chart)
        mBind.chart.setMarker(mv)

        mBind.chart.description.isEnabled = false;
        mBind.chart.setTouchEnabled(true)
        mBind.chart.dragDecelerationFrictionCoef = 0.9f
        mBind.chart.setDragEnabled(true);
        mBind.chart.setScaleEnabled(true);
        mBind.chart.setDrawGridBackground(false);
        mBind.chart.setHighlightPerDragEnabled(true);
        mBind.chart.setPinchZoom(false);
        mBind.chart.setBackgroundColor(resources.getColor(R.color.colorLine));

        mBind.chart.setNoDataText("")
        mBind.chart.setNoDataTextColor(R.color.common_text_color)


        // get the legend (only possible after setting data)
        // get the legend (only possible after setting data)
        val l: Legend = mBind.chart.getLegend()

        // modify the legend ...

        // modify the legend ...
        l.form = Legend.LegendForm.LINE
        l.typeface = tfLight
        l.textSize = 11f
        l.textColor = OfflineDataActivity@ this.resources.getColor(R.color.color_666666)
        l.verticalAlignment = Legend.LegendVerticalAlignment.BOTTOM
        l.horizontalAlignment = Legend.LegendHorizontalAlignment.LEFT
        l.orientation = Legend.LegendOrientation.HORIZONTAL
        l.setDrawInside(false)
//        l.setYOffset(11f);

        //        l.setYOffset(11f);
        val xAxis: XAxis = mBind.chart.getXAxis()
        xAxis.typeface = tfLight
        xAxis.textSize = 11f
        xAxis.textColor = ColorTemplate.getHoloBlue()
        xAxis.setDrawGridLines(false)
        xAxis.setDrawAxisLine(false)

        val leftAxis: YAxis = mBind.chart.getAxisLeft()
        leftAxis.typeface = tfLight
        leftAxis.textColor = ColorTemplate.getHoloBlue()
        leftAxis.axisMaximum = leftMaxValue
        leftAxis.axisMinimum = leftMinValue
        leftAxis.setDrawZeroLine(false)
        leftAxis.setDrawGridLines(false)
        leftAxis.isGranularityEnabled = false
//        leftAxis.valueFormatter = object : ValueFormatter() {
//            override fun getAxisLabel(index: Float, axisBase: AxisBase): String {
//                val stringValue = index.toString()
//                if (stringValue.contains('.')) {
//                    var number = stringValue.length - stringValue.indexOf('.') - 1//小数点个数
//                    if (number >= 2) {
//                        return "" + MyUtil.formatFloat(index, 2, 0.00f) + "℃"
//                    } else {
//                        return "$index℃"
//                    }
//                } else {
//                    return "" + index.toInt() + "℃"
//                }
//            }
//        }

        val rightAxis: YAxis = mBind.chart.getAxisRight()
        rightAxis.typeface = tfLight
        rightAxis.textColor = Color.RED
        rightAxis.axisMaximum = rightMaxValue
        rightAxis.axisMinimum = rightMinValue
        rightAxis.setDrawGridLines(false)
        rightAxis.setDrawZeroLine(false)
        rightAxis.isGranularityEnabled = false
//        rightAxis.valueFormatter = object : ValueFormatter() {
//            override fun getAxisLabel(index: Float, axisBase: AxisBase): String {
//                val stringValue = index.toString()
//                if (stringValue.contains('.')) {
//                    var number = stringValue.length - stringValue.indexOf('.') - 1//小数点个数
//                    if (number >= 2) {
//                        return "" + MyUtil.formatFloat(index, 2, 0.00f) + "MPa"
//                    } else {
//                        return "" + index + "MPa"
//                    }
//                } else {
//                    return "" + index.toInt() + "MPa"
//                }
//            }
//        }
//        mBind.GX1.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
//            Log.e("刷新图表", "刷新图表111 ：" + isChecked)
//            if (roomSize > 0) {
//                mBind.chart.lineData.getDataSetByIndex(0)?.isVisible = isChecked
//                mBind.chart.lineData.getDataSetByIndex(0)?.setDrawValues(isChecked)
////                mBind.chart.data.setDrawValues(isChecked)
//                mBind.chart.notifyDataSetChanged()
//                mBind.chart.invalidate()
//            } else {
//                ToastUtils.show("图表暂无数据")
//            }
//
//        })
        mBind.GX2.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
            Log.e("刷新图表", "刷新图表222 ：" + isChecked)
            if (listData.size > 0) {
                mBind.chart.lineData.getDataSetByIndex(0)?.isVisible = isChecked
                mBind.chart.invalidate()
            }

        })
//        mBind.PT1.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
//            Log.e("刷新图表", "刷新图表33 ：" + isChecked)
//            if (roomSize > 0) {
//                mBind.chart.lineData.getDataSetByIndex(2)?.isVisible = isChecked
//                mBind.chart.invalidate()
//            } else {
//                ToastUtils.show("图表暂无数据")
//            }
//        })
        mBind.PT2.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
            Log.e("刷新图表", "刷新图表444 ：" + isChecked)
            if (listData.size > 0) {
                mBind.chart.lineData.getDataSetByIndex(1)?.isVisible = isChecked
                mBind.chart.invalidate()
            }
        })
//        mBind.yali1.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
//            Log.e("刷新图表", "刷新图表555 ：" + isChecked)
//            if (roomSize > 0) {
//                mBind.chart.lineData.getDataSetByIndex(4)?.isVisible = isChecked
//                mBind.chart.invalidate()
//            } else {
//                ToastUtils.show("图表暂无数据")
//            }
//        })
        mBind.yali1.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
            Log.e("刷新图表", "刷新图表666 ：" + isChecked)
            if (listData.size > 0) {
                mBind.chart.lineData.getDataSetByIndex(2)?.isVisible = isChecked
                mBind.chart.invalidate()
            }
        })


        mBind.seekBar1.setOnSeekBarChangeListener(this)
        mBind.seekBar2.setOnSeekBarChangeListener(this)
        mBind.seekBar3.setOnSeekBarChangeListener(this)
        mBind.seekBar4.setOnSeekBarChangeListener(this)
        mBind.tv1.text = "温度最大值 " + mBind.seekBar1.progress
        mBind.tv2.text = "温度最小值 " + mBind.seekBar2.progress
        mBind.tv3.text = "压力最大值 " + mBind.seekBar3.progress
        mBind.tv4.text = "压力最大值 " + mBind.seekBar4.progress

        mBind.layout1.visibility = View.VISIBLE
        mBind.layout2.visibility = View.GONE
        mBind.layout3.visibility = View.GONE
        mBind.layout4.visibility = View.GONE

        mBind.leftMaxET.setText("" + mBind.seekBar1.progress)
        mBind.leftMinET.setText("" + mBind.seekBar2.progress)
        mBind.rightMaxET.setText("" + mBind.seekBar3.progress)
        mBind.rightMinET.setText("" + mBind.seekBar4.progress)


        mBind.seekBar1.progress =
            mmkv.getInt(ValueKey.SEEK_BAR_KEY_1, mViewModel.leftMaxValue.toInt())
        mBind.seekBar2.progress =
            mmkv.getInt(ValueKey.SEEK_BAR_KEY_2, mViewModel.leftMinValue.toInt())
        mBind.seekBar3.progress =
            mmkv.getInt(ValueKey.SEEK_BAR_KEY_3, mViewModel.rightMaxValue.toInt())
        mBind.seekBar4.progress =
            mmkv.getInt(ValueKey.SEEK_BAR_KEY_4, mViewModel.rightMinValue.toInt())
        hideStatusBar(this)
        mToolbar.visibility = View.GONE
        if (isLandscape(this)) {
            mBind.customToolbar.visibility = View.GONE
            mBind.swipeRefreshLayout.setOnRefreshListener {
                mBind.customToolbar.visibility = View.VISIBLE
                mBind.swipeRefreshLayout.isRefreshing = false
                lifecycleScope.launch {
                    delay(2000)
                    if (mBind.customToolbar.visibility == View.VISIBLE) {
                        mBind.customToolbar.visibility = View.GONE
                    }

                }
            }
        } else {
            mBind.swipeRefreshLayout.isEnabled = false
        }


    }

    override fun onRequestSuccess() {
        mViewModel.values2 = ArrayList<Entry>()
        mViewModel.values4 = ArrayList<Entry>()
        mViewModel.values6 = ArrayList<Entry>()
        if (dataMode != 2) {
            var dataBeanString = mmkv.getString(deviceName, "")
            if (!dataBeanString.isNullOrEmpty()) {
                var resultList = dataBeanString.split("AND")
                if (resultList.size == 5) {
                    excelDeviceName = resultList[0]
                    Log.e("onRequestSuccess", "设备名字  " + excelDeviceName)
                    excelTaskName = resultList[1]
                    excelTaskDec = resultList[2]
                    excelStartTime = resultList[3]
                    excelEndTime = resultList[4]
                }

            }

            WaitDialog.show("查询中，请等待")
            lifecycleScope.launch(Dispatchers.Main) {
                val result = withContext(Dispatchers.IO) {
                    listData = OfflineBase.get(appContext).offlineDao()
                        .getAllByDeviceName(deviceName) as ArrayList<OfflineBean>
                    listData.sortBy { it.time.split("&").get(0).toLong() }
                    listData.size
                }

//            ToastUtils.show(result)
                if (listData.size > 0) {
                    WaitDialog.show("查询成功，共" + result + "条数据，数据处理中")
                    mBind.noDataIv.visibility = View.GONE
                    mBind.tipsLayout.visibility = View.VISIBLE
                    mViewModel.setLineChartData(listData)

                } else {
                    WaitDialog.dismiss(1200)
                }

            }
        } else {
            if (!filePath.isNullOrEmpty()) {
                readExcel(filePath)
            } else {
                ToastUtils.show("文件地址为空")
            }
        }


        mViewModel.mLiveLineData.observe(this, Observer {
            Log.e("测试", "拿到livedata数据开始渲染 " + it.values2.size)
            if (it.values2.size > 0) {
                setDataNew(it)
            }

        })
    }

    override fun onDestroy() {
        super.onDestroy()
        mViewModel.values2 = ArrayList<Entry>()
        mViewModel.values4 = ArrayList<Entry>()
        mViewModel.values6 = ArrayList<Entry>()
        mViewModel.mLiveLineData.value = LineDataBean(
            values2 = mViewModel.values2,
            values4 = mViewModel.values4,
            values6 = mViewModel.values6,
        )
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    fun readExcel(filePath: String) {
        WaitDialog.show("解析中，请等待")
        lifecycleScope.launch(Dispatchers.Main) {
            delay(500)
            try {
                val result = withContext(Dispatchers.IO) {
//                    val csvReader: FileReader = FileReader(filePath)
                    var fis = FileInputStream(File(filePath))
                    var isr = InputStreamReader(fis, "GBK")
                    val bufferedReader = BufferedReader(isr)
                    var line: String
                    bufferedReader.readLine()
                    bufferedReader.readLine()
                    bufferedReader.readLine()
                    bufferedReader.readLine().also {
                        line = it
                        excelDeviceName = line.split(",".toRegex()).dropLastWhile { it.isEmpty() }
                            .toTypedArray()[1]
                        Log.e(
                            "测试",
                            "设备名字111111  " + excelDeviceName
                        )
                    }
                    bufferedReader.readLine().also {
                        line = it
                        excelTaskName = line.split(",".toRegex()).dropLastWhile { it.isEmpty() }
                            .toTypedArray()[1]
                    }
                    bufferedReader.readLine().also {
                        line = it
                        excelTaskDec = line.split(",".toRegex()).dropLastWhile { it.isEmpty() }
                            .toTypedArray()[1]
                    }
                    bufferedReader.readLine().also {
                        line = it
                        excelStartTime = line.split(",".toRegex()).dropLastWhile { it.isEmpty() }
                            .toTypedArray()[1]
                    }
                    bufferedReader.readLine().also {
                        line = it
                        excelEndTime = line.split(",".toRegex()).dropLastWhile { it.isEmpty() }
                            .toTypedArray()[1]
                    }
                    for (i in 0 until 12) {
                        bufferedReader.readLine()
                    }
                    var tempListData = ArrayList<OfflineBean>()
                    try {
                        line = bufferedReader.readLine()
                        Log.e("读取数据", "第一次读取 " + line)
                        while (!line.isNullOrEmpty()) {
//                            Log.e("读取数据", "读取数据读取数据读   " + line)
                            // 分割CSV行数据
                            val data = line.split(",".toRegex()).dropLastWhile { it.isEmpty() }
                                .toTypedArray()
                            val time = data[0]
                            val bzTemp = data[1]
                            val hjTemp = data[2]
                            val hjYl = data[3]
//                            Log.e(
//                                "读取到的值", "  " + time + " " + bzTemp + " " + hjTemp + " " + hjYl
//                            )
                            try {
                                if (!time.isNullOrEmpty() && !bzTemp.isNullOrEmpty() && !hjTemp.isNullOrEmpty() && !hjYl.isNullOrEmpty()) {

                                    var mBean = OfflineBean(
                                        deviceName = deviceName,
                                        deviceMac = "",
                                        dataResult = "",
                                        time = "${(MyUtil.StrToDate(time).time) / 1000}&$deviceName",
                                        currentTaskName = excelTaskName,
                                        gX2 = bzTemp.toFloat(),
                                        pT2 = hjTemp.toFloat(),
                                        pressure2 = hjYl.toFloat()
                                    )
                                    tempListData.add(mBean)

                                }
                                line = bufferedReader.readLine()

                            } catch (e: NumberFormatException) {
                                line = bufferedReader.readLine()
                                Log.e("格式化异常", "数值格式化异常")
                            } catch (e: FormatException) {
                                line = bufferedReader.readLine()
                                Log.e("格式化异常", "时间格式化异常")
                            }

                        }
                    } catch (e: NullPointerException) {
                        e.printStackTrace()
                    }

                    // 关闭文件读取流
                    bufferedReader.close()
                    listData = tempListData
                    listData.size
                }

                if (listData.size > 0) {
                    WaitDialog.show("查询成功，共" + listData.size + "条数据，数据处理中")
                    mBind.noDataIv.visibility = View.GONE
                    mBind.tipsLayout.visibility = View.VISIBLE
                    mViewModel.setLineChartData(listData)

                } else {
                    WaitDialog.dismiss(1200)
                }
            } catch (e: IOException) {
                e.printStackTrace()
            } catch (e: NullPointerException) {
                e.printStackTrace()
                ToastUtils.show("文件内容模板格式错误")
                WaitDialog.dismiss(1200)
            } catch (e: ArrayIndexOutOfBoundsException) {
                e.printStackTrace()
                ToastUtils.show("文件内容模板格式错误")
                WaitDialog.dismiss(1200)
            }

        }

    }

    fun getStartXByTime(startTime: Long): Int {
        var startX = 0
        if ((listData[0].time.split("&").get(0).toLong()) * 1000 > startTime) {
            return 0
        } else if ((listData[listData.size - 1].time.split("&").get(0)
                .toLong()) * 1000 < startTime
        ) {
            return listData.size - 1
        } else {
            for (i in 0 until listData.size) {
                Log.e("getStartXByTime", "getStartXByTime   " + i)
                var timeLong = (listData[i].time.split("&").get(0).toLong()) * 1000
                if (timeLong >= startTime) {
                    startX = i
                    break
                }
            }
        }
        return startX
    }

    fun getEndXByTime(endTime: Long): Int {
        var endX = listData.size - 1
        if (endTime >= (listData[listData.size - 1].time.split("&").get(0).toLong()) * 1000) {
            return endX
        } else if (endTime <= (listData[0].time.split("&").get(0).toLong()) * 1000) {
            return 0
        } else {
            for (i in listData.size - 1 downTo 0) {
                var timeLong = (listData[i].time.split("&").get(0).toLong()) * 1000
                if (timeLong < endTime) {
                    endX = i
                    break
                }
            }
        }
        return endX
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    override fun onBindViewClick() {
        //绑定点击事件
        setOnclickNoRepeat(
            mBind.customToolbar?.getRightId(),
            mBind.chooseStartTime,
            mBind.chooseEndTime,
            mBind.toPDF,
            mBind.toExcel,
            mBind.setChartLayout,
            mBind.setNormalLayout,
            mBind.setStartTime,
            mBind.setEndTime,
            mBind.layout3Back,
            mBind.layout3Confirm,
            mBind.toLayout4,
            mBind.toLayout2,
            mBind.confirmAndToLayout2,
            mBind.changeLayout
        ) {
            when (it) {
                mBind.customToolbar?.getRightId() -> {
                    if (dataMode == 2) {
                        shareFile(filePath)
                    } else {
                        val messageDialog = MessageDialog.show(
                            "提示", "保存Excel到本地并分享?", "确定", "取消"
                        )
                        messageDialog.maxWidth =
                            if (appContext.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE)
                                appContext.resources.displayMetrics.widthPixels / 2 else appContext.resources.displayMetrics.widthPixels
                        messageDialog.okButtonClickListener =
                            OnDialogButtonClickListener { dialog, v ->
                                mViewModel.isShareAction = true
                                dialog.dismiss()
                                saveAndShare()
                                true
                            }

                    }
                }

                mBind.changeLayout -> {
                    if (mBind.changeLayout.text.toString() == "横屏显示") {
                        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
                    } else if (mBind.changeLayout.text.toString() == "竖屏显示") {
                        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
                    }

                }

                mBind.toLayout4 -> {
                    mBind.layout1.visibility = View.GONE
                    mBind.layout2.visibility = View.GONE
                    mBind.layout3.visibility = View.GONE
                    mBind.layout4.visibility = View.VISIBLE
                }

                mBind.toLayout2 -> {
                    mBind.layout1.visibility = View.GONE
                    mBind.layout2.visibility = View.VISIBLE
                    mBind.layout3.visibility = View.GONE
                    mBind.layout4.visibility = View.GONE
                }

                mBind.confirmAndToLayout2 -> {
                    mBind.layout1.visibility = View.GONE
                    mBind.layout2.visibility = View.VISIBLE
                    mBind.layout3.visibility = View.GONE
                    mBind.layout4.visibility = View.GONE
                    var canSave = checkCanSave()
                    if (canSave) {
                        mBind.seekBar1.progress = mBind.leftMaxET.text.toString().toInt()
                        mBind.seekBar2.progress = mBind.leftMinET.text.toString().toInt()
                        mBind.seekBar3.progress = mBind.rightMaxET.text.toString().toInt()
                        mBind.seekBar4.progress = mBind.rightMinET.text.toString().toInt()
                        val leftAxis: YAxis = mBind.chart.getAxisLeft()
                        leftAxis.axisMaximum = mBind.seekBar1.progress.toFloat()
                        leftAxis.axisMinimum = mBind.seekBar2.progress.toFloat()
                        val rightAxis: YAxis = mBind.chart.getAxisRight()
                        rightAxis.axisMaximum = mBind.seekBar3.progress.toFloat()
                        rightAxis.axisMinimum = mBind.seekBar4.progress.toFloat()
                        mBind.chart.notifyDataSetChanged()
                        mBind.chart.invalidate()
                    }
                    Log.e("校验结果", "校验结果  " + canSave)
                }


                mBind.layout3Back -> {
                    mBind.layout1.visibility = View.VISIBLE
                    mBind.layout2.visibility = View.GONE
                    mBind.layout3.visibility = View.GONE
                }

                mBind.layout3Confirm -> {
                    if ("确认并导出PDF" == mBind.layout3Confirm.text.toString().trim()) {
                        //导出pdf
                        if (!mBind.setStartTime.text.toString()
                                .isNullOrEmpty() && !mBind.setEndTime.text.toString()
                                .isNullOrEmpty()
                        ) {
                            lifecycleScope.launch {
                                if (listData.size > 2) {

                                    var startX =
                                        getStartXByTime(MyUtil.StrToDate(mBind.setStartTime.text.toString()).time)

                                    var endX = getEndXByTime(
                                        MyUtil.StrToDate(mBind.setEndTime.text.toString()).time
                                    )
                                    Log.e(
                                        "layout3Confirm",
                                        "layout3Confirm   " + startX + " " + endX
                                    )
                                    if (endX > startX) {
                                        mBind.chart.fitScreen()
                                        mBind.chart.setVisibleXRangeMaximum((endX - startX).toFloat())
                                        mBind.chart.moveViewToX(startX.toFloat())

                                        delay(1000)
                                        mBind.startTime.text = mViewModel.xValueListData.get(startX)
                                        mBind.endTime.text = mViewModel.xValueListData.get(endX)

                                        var max2 =
                                            mViewModel.values2.subList(startX, endX).maxBy { it.y }
                                        var max4 =
                                            mViewModel.values4.subList(startX, endX).maxBy { it.y }
                                        var max6 =
                                            mViewModel.values6.subList(startX, endX).maxBy { it.y }
                                        mBind.maxPressureTv.text = "当前时间轴内最大值 \n板载温度：${
                                            MyUtil.formatFloat(
                                                max2.y, 3, 0.000f
                                            )
                                        }℃ ，时间：" + mViewModel.xValueListData.get(
                                            max2.x.toInt()
                                        ) + "\n环境温度：" + MyUtil.formatFloat(
                                            max4.y, 3, 0.000f
                                        ) + "℃ ，时间：" + mViewModel.xValueListData.get(
                                            max4.x.toInt()
                                        ) + "\n环境压力：" + MyUtil.formatFloat(
                                            max6.y, 3, 0.000f
                                        ) + "MPa ，时间：" + mViewModel.xValueListData.get(
                                            max6.x.toInt()
                                        )


                                        if (listData.size > 0) {
                                            WaitDialog.show("导出中，请等待")
                                            lifecycleScope.launch(Dispatchers.Main) {
                                                var filePath =
                                                    Environment.getExternalStorageDirectory()
                                                        .toString() + "/tpcollection"
                                                delay(200)
                                                val result = withContext(Dispatchers.IO) {
                                                    var resultList = listData.subList(startX, endX)
                                                    var bzMaxBean = resultList.maxBy { it.gX2 }
                                                    var bzMax = MyUtil.formatFloat(
                                                        bzMaxBean.gX2, 2, 0.00f
                                                    )

                                                    var bzMaxTime = MyUtil.DateToStr(
                                                        Date(
                                                            (bzMaxBean.time.split("&").get(0)
                                                                .toLong()) * 1000
                                                        )
                                                    )

                                                    var bzMinBean = resultList.minBy { it.gX2 }
                                                    var bzMin = MyUtil.formatFloat(
                                                        bzMinBean.gX2, 2, 0.00f
                                                    )
                                                    var bzMinTime = MyUtil.DateToStr(
                                                        Date(
                                                            (bzMinBean.time.split("&").get(0)
                                                                .toLong()) * 1000
                                                        )
                                                    )

                                                    var hjMaxBean = resultList.maxBy { it.pT2 }
                                                    var hjMax = MyUtil.formatFloat(
                                                        hjMaxBean.pT2, 3, 0.000f
                                                    )
                                                    var hjMaxTime = MyUtil.DateToStr(
                                                        Date(
                                                            (hjMaxBean.time.split("&").get(0)
                                                                .toLong()) * 1000
                                                        )
                                                    )
                                                    var hjMinBean = resultList.minBy { it.pT2 }
                                                    var hjMin = MyUtil.formatFloat(
                                                        hjMinBean.pT2, 3, 0.00f
                                                    )

                                                    var hjMinTime = MyUtil.DateToStr(
                                                        Date(
                                                            (hjMinBean.time.split("&").get(0)
                                                                .toLong()) * 1000
                                                        )
                                                    )

                                                    var ylMaxBean =
                                                        resultList.maxBy { it.pressure2 }
                                                    var ylMax = MyUtil.formatFloat(
                                                        ylMaxBean.pressure2, 3, 0.000f
                                                    )
                                                    var ylMaxTime = MyUtil.DateToStr(
                                                        Date(
                                                            (ylMaxBean.time.split("&").get(0)
                                                                .toLong()) * 1000
                                                        )
                                                    )

                                                    var ylMinBean =
                                                        resultList.minBy { it.pressure2 }
                                                    var ylMin = MyUtil.formatFloat(
                                                        ylMinBean.pressure2, 3, 0.000f
                                                    )
                                                    var ylMinTime = MyUtil.DateToStr(
                                                        Date(
                                                            (ylMinBean.time.split("&").get(0)
                                                                .toLong()) * 1000
                                                        )
                                                    )

                                                    var deviceName =
                                                        mmkv.getString(
                                                            ValueKey.CURRENT_DEVICE_NAME,
                                                            ""
                                                        )
                                                            .toString()
                                                    var taskName =
                                                        mmkv.getString(
                                                            ValueKey.CURRENT_TASK_NAME,
                                                            ""
                                                        )
                                                            .toString()
                                                    var taskDec =
                                                        mmkv.getString(
                                                            ValueKey.CURRENT_TASK_DEC,
                                                            ""
                                                        )
                                                            .toString()

                                                    var file = File(filePath)
                                                    if (!file.exists()) {
                                                        file.mkdirs()
                                                    }

                                                    var currentTime = MyUtil.DateToStrFormat(Date())
                                                    var excelFileName: String = "/${
                                                        excelDeviceName.toString().trim()
                                                            .replace("?", "")
                                                    }_${excelTaskName}_报表_$currentTime.pdf"
                                                    filePath += excelFileName;
                                                    Log.e("导出路径", "导出路径   " + filePath)
                                                    val mfile: File = File(filePath)
                                                    if (!mfile.exists()) {
                                                        mfile.createNewFile()
                                                    }
                                                    var pdfDocument =
                                                        PdfDocument(PdfWriter(filePath))

                                                    var info = pdfDocument.documentInfo

                                                    info.setTitle("")
                                                    info.setAuthor("")
                                                    info.setCreator("")


                                                    // 创建一个页面
                                                    val document =
                                                        Document(pdfDocument, PageSize.A4, true)

                                                    var font: PdfFont? = null
                                                    try {
                                                        font = PdfFontFactory.createFont(
                                                            "STSong-Light", "UniGB-UCS2-H"
                                                        )
                                                    } catch (e: IOException) {
                                                        Log.e("IOException", e.toString())
                                                        Log.e("测试", "测试，有异常异常")
                                                    }
                                                    var title_size = 24.0f
                                                    var text_title_size = 24.0f
                                                    var text_size = 13.0f
                                                    var title_color = DeviceRgb(0, 0, 0)
                                                    var text_title_color = DeviceRgb(65, 136, 160)
                                                    var text_color = DeviceRgb(43, 43, 43)

                                                    var drawable =
                                                        resources.getDrawable(R.mipmap.icon_laucher)

                                                    var bitmap = MyUtil.drawableToBitamp(drawable)


                                                    var bytes = MyUtil.convertToBytes(bitmap)

                                                    var imageData = ImageDataFactory.create(bytes)
                                                    var image =
                                                        com.itextpdf.layout.element.Image(imageData)
                                                            .setWidth(PageSize.A4.getWidth() / 4)


                                                    var pointColumnWidths = floatArrayOf(
                                                        PageSize.A4.getWidth() / 4 * 3,
                                                        PageSize.A4.getWidth() / 4
                                                    )
                                                    var table = Table(pointColumnWidths)


                                                    var table_color = DeviceRgb(255, 255, 255);
                                                    var border = DottedBorder(table_color, 2f);
                                                    table.setBorder(border)
                                                    table.setTextAlignment(TextAlignment.LEFT)
                                                    var contentString =
                                                        "测量单位：四川川庆石油钻采科技有限公司\n" + "设备名称：$excelDeviceName\n" + "任务名称：$excelTaskName\n" + "任务备注：$excelTaskDec\n" + "板载温度最大值(℃)：$bzMax" + "\t时间：$bzMaxTime\n" + "板载温度最小值(℃)：$bzMin" + "\t时间：$bzMinTime\n" + "环境温度最大值(℃)：$hjMax" + "\t时间：$hjMaxTime\n" + "环境温度最小值(℃)：$hjMin" + "\t时间：$hjMinTime\n" + "环境压力最大值(MPa)：$ylMax" + "\t时间：$ylMaxTime\n" + "环境压力最小值(MPa)：$ylMin" + "\t时间：$ylMinTime"
                                                    var test = Text(contentString).setFont(font)
                                                        .setFontSize(text_size)
                                                        .setFontColor(text_color)

                                                    table.addCell(Paragraph(test))
                                                    table.addCell(Paragraph().add(image))
                                                    table.getCell(0, 0).setBorder(border)
                                                    document.add(table)

                                                    var bitmap1 = Bitmap.createBitmap(
                                                        mBind.pdfLayout.width,
                                                        mBind.pdfLayout.height,
                                                        Bitmap.Config.ARGB_8888
                                                    )
                                                    // 创建画布对象
                                                    val canvas = Canvas(bitmap1)
                                                    canvas.drawColor(Color.WHITE)
                                                    // 将视图绘制到画布上
                                                    mBind.pdfLayout.draw(canvas)

                                                    var bytes1 = MyUtil.convertToBytes(bitmap1)

                                                    var pageWidth = PageSize.A4.getWidth()
                                                    var pageHeight = PageSize.A4.height
                                                    var imageData1 = ImageDataFactory.create(bytes1)
                                                    var image1 =
                                                        com.itextpdf.layout.element.Image(imageData1)
                                                            .setWidth(pageWidth * 4 / 5)
                                                            .setHeight(pageHeight * 3 / 5)

                                                    document.add(
                                                        Paragraph().setTextAlignment(TextAlignment.CENTER)
                                                            .add(image1)
                                                    )

                                                    document.close()
                                                    true
                                                }
                                                if (result) {
                                                    WaitDialog.dismiss(100)
                                                    ToastUtils.show("生成PDF成功,文件位置:$filePath")
                                                } else {
                                                    WaitDialog.dismiss(100)
                                                    ToastUtils.show("生成PDF失败")
                                                }
                                                mBind.chart.setVisibleXRangeMaximum(listData.size.toFloat())
                                            }
                                        } else {
                                            ToastUtils.show("暂无数据")
                                        }
                                    } else {
                                        ToastUtils.show("结束时间不得早于开始时间！")
                                    }

                                } else {
                                    ToastUtils.show("暂无数据")
                                }


                            }

                        } else {
                            ToastUtils.show("请先选择时间再操作")
                        }
                    } else {
                        //导出excel
                        if (!mBind.setStartTime.text.toString()
                                .isNullOrEmpty() && !mBind.setEndTime.text.toString()
                                .isNullOrEmpty()
                        ) {
                            lifecycleScope.launch {
                                if (listData.size > 2) {

                                    var startX =
                                        getStartXByTime(MyUtil.StrToDate(mBind.setStartTime.text.toString()).time)

                                    var endX = getEndXByTime(
                                        MyUtil.StrToDate(mBind.setEndTime.text.toString()).time
                                    )
                                    Log.e(
                                        "layout3Confirm",
                                        "layout3Confirm   " + startX + " " + endX
                                    )
                                    if (endX > startX) {
                                        var resultList = listData.subList(startX, endX)
                                        if (resultList.size > 0) {
                                            if (resultList.size > 0) {
                                                val messageDialog = InputDialog(
                                                    "请输入测量间隔", "单位:（S）", "确定", "取消", ""
                                                )
                                                messageDialog.maxWidth =
                                                    if (appContext.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE)
                                                        appContext.resources.displayMetrics.widthPixels / 2 else appContext.resources.displayMetrics.widthPixels
                                                messageDialog.setInputText("1")
                                                    .setOkButton { baseDialog, v, inputStr ->
                                                        try {
                                                            var filePath =
                                                                Environment.getExternalStorageDirectory()
                                                                    .toString() + "/tpcollection"
                                                            WaitDialog.show("导出中，请等待")
                                                            lifecycleScope.launch(Dispatchers.Main) {
                                                                delay(200)
                                                                val result =
                                                                    withContext(Dispatchers.IO) {
                                                                        var delayTime =
                                                                            inputStr.trim().toInt()
                                                                        var resultList =
                                                                            getListDataByDelay(
                                                                                resultList,
                                                                                delayTime
                                                                            )


                                                                        var bzMaxBean =
                                                                            resultList.maxBy { it.gX2 }
                                                                        var bzMax =
                                                                            MyUtil.formatFloat(
                                                                                bzMaxBean.gX2,
                                                                                2,
                                                                                0.00f
                                                                            )

                                                                        var bzMaxTime =
                                                                            MyUtil.DateToStr(
                                                                                Date(
                                                                                    (bzMaxBean.time.split(
                                                                                        "&"
                                                                                    ).get(0)
                                                                                        .toLong()) * 1000
                                                                                )
                                                                            )

                                                                        var bzMinBean =
                                                                            resultList.minBy { it.gX2 }
                                                                        var bzMin =
                                                                            MyUtil.formatFloat(
                                                                                bzMinBean.gX2,
                                                                                2,
                                                                                0.00f
                                                                            )
                                                                        var bzMinTime =
                                                                            MyUtil.DateToStr(
                                                                                Date(
                                                                                    (bzMinBean.time.split(
                                                                                        "&"
                                                                                    ).get(0)
                                                                                        .toLong()) * 1000
                                                                                )
                                                                            )

                                                                        var hjMaxBean =
                                                                            resultList.maxBy { it.pT2 }
                                                                        var hjMax =
                                                                            MyUtil.formatFloat(
                                                                                hjMaxBean.pT2,
                                                                                3,
                                                                                0.000f
                                                                            )
                                                                        var hjMaxTime =
                                                                            MyUtil.DateToStr(
                                                                                Date(
                                                                                    (hjMaxBean.time.split(
                                                                                        "&"
                                                                                    ).get(0)
                                                                                        .toLong()) * 1000
                                                                                )
                                                                            )

                                                                        var hjMinBean =
                                                                            resultList.minBy { it.pT2 }
                                                                        var hjMin =
                                                                            MyUtil.formatFloat(
                                                                                hjMinBean.pT2,
                                                                                3,
                                                                                0.00f
                                                                            )

                                                                        var hjMinTime =
                                                                            MyUtil.DateToStr(
                                                                                Date(
                                                                                    (hjMinBean.time.split(
                                                                                        "&"
                                                                                    ).get(0)
                                                                                        .toLong()) * 1000
                                                                                )
                                                                            )

                                                                        var ylMaxBean =
                                                                            resultList.maxBy { it.pressure2 }
                                                                        var ylMax =
                                                                            MyUtil.formatFloat(
                                                                                ylMaxBean.pressure2,
                                                                                3,
                                                                                0.000f
                                                                            )
                                                                        var ylMaxTime =
                                                                            MyUtil.DateToStr(
                                                                                Date(
                                                                                    (ylMaxBean.time.split(
                                                                                        "&"
                                                                                    ).get(0)
                                                                                        .toLong()) * 1000
                                                                                )
                                                                            )

                                                                        var ylMinBean =
                                                                            resultList.minBy { it.pressure2 }
                                                                        var ylMin =
                                                                            MyUtil.formatFloat(
                                                                                ylMinBean.pressure2,
                                                                                3,
                                                                                0.000f
                                                                            )
                                                                        var ylMinTime =
                                                                            MyUtil.DateToStr(
                                                                                Date(
                                                                                    (ylMinBean.time.split(
                                                                                        "&"
                                                                                    ).get(0)
                                                                                        .toLong()) * 1000
                                                                                )
                                                                            )


                                                                        var file = File(filePath)
                                                                        if (!file.exists()) {
                                                                            file.mkdirs()
                                                                        }
                                                                        var currentTime =
                                                                            MyUtil.DateToStrFormat(
                                                                                Date()
                                                                            )
                                                                        var excelFileName: String =
                                                                            "/${
                                                                                excelDeviceName
                                                                            }_${excelTaskName}_$currentTime.csv"
                                                                        filePath += excelFileName;
                                                                        Log.e(
                                                                            "目录",
                                                                            "目录  " + filePath
                                                                        )
                                                                        var title = arrayOf(
                                                                            "时间",
                                                                            "板载温度(℃)",
                                                                            "环境温度(℃)",
                                                                            "环境压力(MPa)"
                                                                        )

                                                                        ExcelUtil.writeToExcel(
                                                                            filePath,
                                                                            title,
                                                                            "四川川庆石油钻采科技有限公司",
                                                                            excelDeviceName,
                                                                            excelTaskName,
                                                                            excelTaskDec,
                                                                            excelStartTime,
                                                                            excelEndTime,
                                                                            "" + delayTime,
                                                                            "" + bzMax,
                                                                            "" + bzMin,
                                                                            bzMaxTime,
                                                                            bzMinTime,
                                                                            "" + hjMax,
                                                                            "" + hjMin,
                                                                            "" + hjMaxTime,
                                                                            "" + hjMinTime,
                                                                            "" + ylMax,
                                                                            "" + ylMin,
                                                                            "" + ylMaxTime,
                                                                            "" + ylMinTime,
                                                                            resultList
                                                                        );

                                                                    }
                                                                if (result) {
                                                                    WaitDialog.dismiss(100)
                                                                    ToastUtils.show("导出Excel成功,文件位置:$filePath")
                                                                    if (mViewModel.isShareAction == true) {
                                                                        shareFile(filePath)
                                                                    }
                                                                } else {
                                                                    WaitDialog.dismiss(100)
                                                                    ToastUtils.show("导出Excel失败")
                                                                }

                                                            }

                                                        } catch (e: NumberFormatException) {
                                                            ToastUtils.show("请输入正确的值")
                                                        }

                                                        false
                                                    }.show()
                                            } else {
                                                ToastUtils.show("暂无数据")
                                            }
                                        } else {
                                            ToastUtils.show("暂无数据")
                                        }
                                    } else {
                                        ToastUtils.show("结束时间不得早于开始时间！")
                                    }

                                } else {
                                    ToastUtils.show("暂无数据")
                                }


                            }

                        } else {
                            ToastUtils.show("请先选择时间再操作")
                        }
                    }

                    mBind.layout1.visibility = View.VISIBLE
                    mBind.layout2.visibility = View.GONE
                    mBind.layout3.visibility = View.GONE
                }

                mBind.setStartTime -> {
                    if (listData.size > 2) {
                        var picker = DatimePicker(this)
                        var wheelLayout = picker.wheelLayout
                        picker.setOnDatimePickedListener { year, month, day, hour, minute, second ->
                            var text = "$year-$month-$day $hour:$minute:$second"
                            mBind.setStartTime.text = MyUtil.DateToStr(MyUtil.StrToDate(text))

                        }

                        val entity = DatimeEntity()

                        var startDate = Date((listData[0].time.split("&").get(0).toLong()) * 1000)

                        entity.date = DateEntity.target(startDate)
                        entity.time = TimeEntity.target(
                            Date(
                                (listData[0].time.split("&").get(0).toLong() - 60) * 1000
                            )
                        )
                        wheelLayout.setDateMode(DateMode.YEAR_MONTH_DAY)
                        wheelLayout.setTimeMode(TimeMode.HOUR_24_NO_SECOND)
                        wheelLayout.setRange(entity, DatimeEntity.yearOnFuture(10))
                        wheelLayout.setDateLabel("年", "月", "日")
                        wheelLayout.setTimeLabel("时", "分", "秒")
                        picker.show()
                    } else {
                        ToastUtils.show("暂无数据")
                    }

                }

                mBind.setEndTime -> {
                    if (listData.size > 2) {
                        var picker = DatimePicker(this)
                        var wheelLayout = picker.wheelLayout
                        picker.setOnDatimePickedListener { year, month, day, hour, minute, second ->
                            var text = "$year-$month-$day $hour:$minute:$second"
                            mBind.setEndTime.text = MyUtil.DateToStr(MyUtil.StrToDate(text))

                        }

                        val entity = DatimeEntity()

                        var endDate = Date(
                            (listData[0].time.split("&").get(0).toLong()) * 1000
                        )

                        entity.date = DateEntity.target(endDate)
                        entity.time = TimeEntity.target(
                            Date(
                                (listData[listData.size - 1].time.split("&").get(0)
                                    .toLong() + 60) * 1000
                            )
                        )
                        wheelLayout.setDateMode(DateMode.YEAR_MONTH_DAY)
                        wheelLayout.setTimeMode(TimeMode.HOUR_24_NO_SECOND)
                        wheelLayout.setRange(entity, DatimeEntity.yearOnFuture(10))
                        wheelLayout.setDateLabel("年", "月", "日")
                        wheelLayout.setTimeLabel("时", "分", "秒")
                        picker.show()
                    } else {
                        ToastUtils.show("暂无数据")
                    }
                }

                mBind.setNormalLayout -> {
                    mBind.layout1.visibility = View.VISIBLE
                    mBind.layout2.visibility = View.GONE
                    mBind.layout3.visibility = View.GONE
                }

                mBind.setChartLayout -> {
                    mBind.layout1.visibility = View.GONE
                    mBind.layout2.visibility = View.VISIBLE
                    mBind.layout3.visibility = View.GONE

                }

                mBind.toPDF -> {
                    mBind.layout1.visibility = View.GONE
                    mBind.layout2.visibility = View.GONE
                    mBind.layout3.visibility = View.VISIBLE
                    mBind.layout3Confirm.text = "确认并导出PDF"
                    if (listData.size > 2) {
                        mBind.setStartTime.text = MyUtil.DateToStr(
                            Date(
                                (listData[0].time.split("&").get(0).toLong()) * 1000
                            )
                        )
                        mBind.setEndTime.text = MyUtil.DateToStr(
                            Date(
                                (listData[listData.size - 1].time.split("&").get(0).toLong()) * 1000
                            )
                        )
                    }
                }

                mBind.chooseStartTime -> {


                }

                mBind.toExcel -> {
                    mBind.layout1.visibility = View.GONE
                    mBind.layout2.visibility = View.GONE
                    mBind.layout3.visibility = View.VISIBLE
                    mBind.layout3Confirm.text = "确认并导出Excel"
                    mViewModel.isShareAction = false
                    if (listData.size > 2) {
                        mBind.setStartTime.text = MyUtil.DateToStr(
                            Date(
                                (listData[0].time.split("&").get(0).toLong()) * 1000
                            )
                        )
                        mBind.setEndTime.text = MyUtil.DateToStr(
                            Date(
                                (listData[listData.size - 1].time.split("&").get(0).toLong()) * 1000
                            )
                        )
                    }

                }

                mBind.chooseStartTime -> {
                    var picker = DatimePicker(this)
                    var wheelLayout = picker.wheelLayout
                    picker.setOnDatimePickedListener { year, month, day, hour, minute, second ->
                        var text = "$year-$month-$day $hour:$minute:$second"
                        mBind.chooseStartTime.text = MyUtil.DateToStr(MyUtil.StrToDate(text))
                        var timeByteArray: ByteArray = byteArrayOf(
                            year.toString().substring(2, 4).toInt().toByte(),
                            month.toByte(),
                            day.toByte(),
                            hour.toByte(),
                            minute.toByte(),
                            second.toByte()
                        )
                        Log.e("选择的时间", "选择的开始时间 ：" + MyUtil.bytes2Hex(timeByteArray))
                        mmkv.putString(
                            ValueKey.COLLECTION_START_TIME_CMD, MyUtil.bytes2Hex(timeByteArray)
                        )
                    }

                    val entity = DatimeEntity()
                    var startDate = Date((minLong + 8 * 3600) * 1000)
                    entity.date = DateEntity.target(startDate)
                    entity.time = TimeEntity.now()
                    wheelLayout.setDateMode(DateMode.YEAR_MONTH_DAY)
                    wheelLayout.setTimeMode(TimeMode.HOUR_24_NO_SECOND)
                    wheelLayout.setRange(entity, DatimeEntity.yearOnFuture(10))
                    wheelLayout.setDateLabel("年", "月", "日")
                    wheelLayout.setTimeLabel("时", "分", "秒")
                    picker.show()

                }

                mBind.chooseEndTime -> {
                    var picker = DatimePicker(this)
                    var wheelLayout = picker.wheelLayout
                    picker.setOnDatimePickedListener { year, month, day, hour, minute, second ->
                        var text = "$year-$month-$day $hour:$minute:$second"
                        mBind.chooseEndTime.text = MyUtil.DateToStr(MyUtil.StrToDate(text))
                        var timeByteArray: ByteArray = byteArrayOf(
                            year.toString().substring(2, 4).toInt().toByte(),
                            month.toByte(),
                            day.toByte(),
                            hour.toByte(),
                            minute.toByte(),
                            second.toByte()
                        )
                        Log.e("选择的时间", "选择的结束时间 ：" + MyUtil.bytes2Hex(timeByteArray))
                        mmkv.putString(
                            ValueKey.COLLECTION_END_TIME_CMD, MyUtil.bytes2Hex(timeByteArray)
                        )
                    }
                    wheelLayout.setDateMode(DateMode.YEAR_MONTH_DAY)
                    wheelLayout.setTimeMode(TimeMode.HOUR_24_NO_SECOND)
                    val entity = DatimeEntity()
                    var startDate = Date((minLong + 8 * 3600) * 1000)
                    entity.date = DateEntity.target(startDate)
                    entity.time = TimeEntity.now()

                    wheelLayout.setRange(entity, DatimeEntity.yearOnFuture(10))
                    wheelLayout.setDateLabel("年", "月", "日")
                    wheelLayout.setTimeLabel("时", "分", "秒")
                    picker.show()
                }
            }
        }
    }

    private fun shareFile(filePath: String) {
        Log.e("shareFile", "shareFile :    " + filePath)
        val builder = StrictMode.VmPolicy.Builder()
        StrictMode.setVmPolicy(builder.build())
        builder.detectFileUriExposure()
        val intent = Intent(Intent.ACTION_SEND)
        var currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= 24) {
            val uri = FileProvider.getUriForFile(
                this.getApplicationContext(),
                "com.tazan.temperature.collect.provider",
                File(filePath)
            );
            intent.putExtra(Intent.EXTRA_STREAM, uri)
            intent.type = "application/octet-stream"
//            intent.addCategory(Intent.CATEGORY_DEFAULT);
        } else {
            val uri = Uri.fromFile(File(filePath));
//            val uri = FileProvider.getUriForFile(
//                this.getApplicationContext(),
//                "com.tazan.temperature.collect.provider",
//                File(filePath)
//            );
            intent.putExtra(Intent.EXTRA_STREAM, uri)
            intent.type = "application/octet-stream"
//            intent.addCategory(Intent.CATEGORY_DEFAULT);
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
        // 创建一个新的Intent来启动分享列表
        // 创建一个新的Intent来启动分享列表
        val chooserIntent = Intent.createChooser(intent, "分享到")
        val resolveInfos = this.packageManager.queryIntentActivities(intent, 0)
        startActivity(chooserIntent)
    }

    private fun saveAndShare() {
        if (listData.size > 0) {
            mBind.layout1.visibility = View.GONE
            mBind.layout2.visibility = View.GONE
            mBind.layout3.visibility = View.VISIBLE
            mBind.layout3Confirm.text = "确认并导出Excel"
            if (listData.size > 2) {
                mBind.setStartTime.text = MyUtil.DateToStr(
                    Date(
                        (listData[0].time.split("&").get(0).toLong()) * 1000
                    )
                )
                mBind.setEndTime.text = MyUtil.DateToStr(
                    Date(
                        (listData[listData.size - 1].time.split("&").get(0).toLong()) * 1000
                    )
                )
            }
        } else {
            ToastUtils.show("暂无数据")
        }
    }

    private fun checkCanSave(): Boolean {
        var canSave = true
        try {
            var leftMax = mBind.leftMaxET.text.toString().toInt()
            var leftMin = mBind.leftMinET.text.toString().toInt()
            var rightMax = mBind.rightMaxET.text.toString().toInt()
            var rightMin = mBind.rightMinET.text.toString().toInt()
            canSave =
                leftMax >= mViewModel.leftMinValue && leftMax <= mViewModel.leftMaxValue && leftMin >= mViewModel.leftMinValue && leftMin <= mViewModel.leftMaxValue && rightMax >= mViewModel.rightMinValue && rightMax <= mViewModel.rightMaxValue && rightMin >= mViewModel.rightMinValue && rightMin <= mViewModel.rightMaxValue
            if (!canSave) {
                ToastUtils.show("请输入在正确范围内的数值")
            }
        } catch (e: NumberFormatException) {
            Log.e("解析异常", "解析异常 ")
            ToastUtils.show("请输入在正确格式的参数")
            canSave = false
        }

        return canSave
    }

    fun getListDataByDelay(
        listData: List<OfflineBean>,
        delayTime: Int
    ): ArrayList<OfflineBean> {
        var result = ArrayList<OfflineBean>()
        var tempTime: Long = 0
        if (listData.size > 2) {
            for (i in 0 until listData.size) {
                if (i == 0) {
                    result.add(listData.get(i))
                    tempTime = listData.get(i).time.split("&").get(0).toLong()
                } else {
                    var time = listData.get(i).time.split("&").get(0).toLong()
                    if (time - tempTime >= delayTime) {
                        result.add(listData.get(i))
                        tempTime = time
                    }
                }

            }
        }

        return result
    }


    private fun setDataNew(mLineData: LineDataBean) {
        if (mViewModel.xValueListData.size > 0) {
            mBind.startTime.text = mViewModel.xValueListData.get(0)
            mBind.endTime.text = mViewModel.xValueListData.get(mViewModel.xValueListData.size - 1)
            var max2 = mViewModel.values2.maxBy { it.y }
            var max4 = mViewModel.values4.maxBy { it.y }
            var max6 = mViewModel.values6.maxBy { it.y }
            mBind.maxPressureTv.text = "当前时间轴内最大值 \n板载温度：${
                MyUtil.formatFloat(
                    max2.y, 3, 0.000f
                )
            }℃ ，时间：" + mViewModel.xValueListData.get(
                max2.x.toInt()
            ) + "\n环境温度：" + MyUtil.formatFloat(
                max4.y, 3, 0.000f
            ) + "℃ ，时间：" + mViewModel.xValueListData.get(
                max4.x.toInt()
            ) + "\n环境压力：" + MyUtil.formatFloat(
                max6.y, 3, 0.000f
            ) + "MPa ，时间：" + mViewModel.xValueListData.get(
                max6.x.toInt()
            )

            mBind.chart.setOnTouchListener(View.OnTouchListener { v, event ->
                var visibleXStart = mBind.chart.getLowestVisibleX().toInt()
                var visibleXEnd = mBind.chart.getHighestVisibleX().toInt()
                mBind.startTime.text = mViewModel.xValueListData.get(visibleXStart)
                mBind.endTime.text = mViewModel.xValueListData.get(visibleXEnd)
                if (event.action == MotionEvent.ACTION_UP) {
                    if (visibleXEnd - visibleXStart >= 2) {

                        var max2 =
                            mViewModel.values2.subList(visibleXStart, visibleXEnd).maxBy { it.y }
                        var max4 =
                            mViewModel.values4.subList(visibleXStart, visibleXEnd).maxBy { it.y }
                        var max6 =
                            mViewModel.values6.subList(visibleXStart, visibleXEnd).maxBy { it.y }
                        mBind.maxPressureTv.text = "当前时间轴内最大值 \n板载温度：${
                            MyUtil.formatFloat(
                                max2.y, 3, 0.000f
                            )
                        }℃ ，时间：" + mViewModel.xValueListData.get(
                            max2.x.toInt()
                        ) + "\n环境温度：" + MyUtil.formatFloat(
                            max4.y, 3, 0.000f
                        ) + "℃ ，时间：" + mViewModel.xValueListData.get(
                            max4.x.toInt()
                        ) + "\n环境压力：" + MyUtil.formatFloat(
                            max6.y, 3, 0.000f
                        ) + "MPa ，时间：" + mViewModel.xValueListData.get(
                            max6.x.toInt()
                        )
                    }


                }
                false
            })
        }
        var line1Color = resources.getColor(colorIntList[mmkv.getInt(ValueKey.COLOR1, 0)])
        var line2Color = resources.getColor(colorIntList[mmkv.getInt(ValueKey.COLOR2, 2)])
        var line3Color = resources.getColor(colorIntList[mmkv.getInt(ValueKey.COLOR3, 8)])

//        val set1: LineDataSet
        val set2: LineDataSet
//        val set3: LineDataSet
        val set4: LineDataSet
//        val set5: LineDataSet
        val set6: LineDataSet
        if (mBind.chart.getData() != null && mBind.chart.getData().getDataSetCount() > 0) {
//            set1 = mBind.chart.getData().getDataSetByIndex(0) as LineDataSet
            set2 = mBind.chart.getData().getDataSetByIndex(0) as LineDataSet
            set2.color = line1Color
            set2.fillColor = line1Color
//            set3 = mBind.chart.getData().getDataSetByIndex(2) as LineDataSet
            set4 = mBind.chart.getData().getDataSetByIndex(1) as LineDataSet
            set4.color = line2Color
            set4.fillColor = line2Color
//            set5 = mBind.chart.getData().getDataSetByIndex(4) as LineDataSet
            set6 = mBind.chart.getData().getDataSetByIndex(2) as LineDataSet
            set6.color = line3Color
            set6.fillColor = line3Color
//            set1.values = mLineData.values1
            set2.values = mLineData.values2
//            set3.values = mLineData.values3
            set4.values = mLineData.values4
//            set5.values = mLineData.values5
            set6.values = mLineData.values6
//            set7.values = mLineData.values7
            mBind.chart.getData().notifyDataChanged()
            mBind.chart.notifyDataSetChanged()
        } else {
            // create a dataset and give it a type
//            set1 = LineDataSet(mLineData.values1, "温度1")
//            set1.axisDependency = YAxis.AxisDependency.LEFT
//            set1.color = ColorTemplate.getHoloBlue()
//            set1.setCircleColor(Color.WHITE)
//            set1.lineWidth = 2f
//            set1.circleRadius = 3f
//            set1.fillAlpha = 65
//            set1.fillColor = ColorTemplate.getHoloBlue()
//            set1.highLightColor = Color.rgb(244, 117, 117)
//            set1.setDrawCircleHole(false)
//            set1.setDrawCircles(false)
//            set1.setDrawValues(false)
            //set1.setFillFormatter(new MyFillFormatter(0f));
            //set1.setDrawHorizontalHighlightIndicator(false);
            //set1.setVisible(false);
            //set1.setCircleHoleColor(Color.WHITE);

            set2 = LineDataSet(mLineData.values2, "板载温度")
            set2.axisDependency = YAxis.AxisDependency.LEFT
            set2.color = line1Color
            set2.setCircleColor(Color.WHITE)
            set2.lineWidth = 2f
            set2.circleRadius = 3f
            set2.fillAlpha = 65
            set2.fillColor = line1Color
            set2.setDrawCircleHole(false)
            set2.setDrawCircles(false)
            set2.setDrawValues(false)
            set2.highLightColor = Color.rgb(244, 117, 117)

//            set3 = LineDataSet(mLineData.values3, "温度3")
//            set3.axisDependency = YAxis.AxisDependency.LEFT
//            set3.color = Color.GREEN
//            set3.setCircleColor(Color.WHITE)
//            set3.lineWidth = 2f
//            set3.circleRadius = 3f
//            set3.fillAlpha = 65
//            set3.fillColor = Color.GREEN
//            set3.setDrawCircleHole(false)
//            set3.setDrawCircles(false)
//            set3.setDrawValues(false)
//            set3.highLightColor = Color.rgb(244, 117, 117)

            set4 = LineDataSet(mLineData.values4, "环境温度")
            set4.axisDependency = YAxis.AxisDependency.LEFT
            set4.color = line2Color
            set4.setCircleColor(Color.WHITE)
            set4.lineWidth = 2f
            set4.circleRadius = 3f
            set4.fillAlpha = 65
            set4.fillColor = line2Color
            set4.setDrawCircleHole(false)
            set4.setDrawCircles(false)
            set4.setDrawValues(false)
            set4.highLightColor = Color.rgb(244, 117, 117)

//            set5 = LineDataSet(mLineData.values5, "压力1")
//            set5.axisDependency = YAxis.AxisDependency.RIGHT
//            set5.color = Color.DKGRAY
//            set5.setCircleColor(Color.WHITE)
//            set5.lineWidth = 2f
//            set5.circleRadius = 3f
//            set5.fillAlpha = 65
//            set5.fillColor = Color.DKGRAY
//            set5.setDrawCircleHole(false)
//            set5.setDrawCircles(false)
//            set5.setDrawValues(false)
//            set5.highLightColor = Color.rgb(244, 117, 117)

            set6 = LineDataSet(mLineData.values6, "环境压力")
            set6.axisDependency = YAxis.AxisDependency.RIGHT
            set6.color = line3Color
            set6.setCircleColor(Color.WHITE)
            set6.lineWidth = 2f
            set6.circleRadius = 3f
            set6.fillAlpha = 65
            set6.fillColor = line3Color
            set6.setDrawCircleHole(false)
            set6.setDrawCircles(false)
            set6.setDrawValues(false)
            set6.highLightColor = Color.rgb(244, 117, 117)


            // create a data object with the data sets
            val data = LineData(set2, set4, set6)
            data.setValueTextColor(Color.WHITE)
            data.setValueTextSize(9f)

            // set data
            mBind.chart.setData(data)
            mBind.chart.invalidate()


        }
    }

    override fun onValueSelected(e: Entry?, h: Highlight?) {
        e?.let {
            mBind.chart.centerViewToAnimated(
                it.x, e.y, h?.let { it1 ->
                    mBind.chart.data.getDataSetByIndex(it1.dataSetIndex).axisDependency
                }, 500
            )
        };
    }

    override fun onNothingSelected() {

    }

    override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
//        Log.e("onProgressChanged", "onProgressChanged " + progress)
        when (seekBar?.id) {
            mBind.seekBar1.id -> {
                Log.e("onProgressChanged", "操作最大值 " + progress)
                mmkv.putInt(ValueKey.SEEK_BAR_KEY_1, progress)
                mBind.tv1.text = "温度最大值" + mBind.seekBar1.progress
                mBind.leftMaxET.setText("" + mBind.seekBar1.progress)
                val leftAxis: YAxis = mBind.chart.getAxisLeft()
                leftAxis.axisMaximum = progress.toFloat()
                mBind.chart.notifyDataSetChanged()
                mBind.chart.invalidate()
            }

            mBind.seekBar2.id -> {
                Log.e("onProgressChanged", "操作最小值 " + progress)
                mmkv.putInt(ValueKey.SEEK_BAR_KEY_2, progress)
                mBind.tv2.text = "温度最小值" + mBind.seekBar2.progress
                mBind.leftMinET.setText("" + mBind.seekBar2.progress)
                val leftAxis: YAxis = mBind.chart.getAxisLeft()
                leftAxis.axisMinimum = progress.toFloat()
                mBind.chart.notifyDataSetChanged()
                mBind.chart.invalidate()
            }

            mBind.seekBar3.id -> {
                Log.e("onProgressChanged", "操作右边最大值 " + progress)
                mmkv.putInt(ValueKey.SEEK_BAR_KEY_3, progress)
                mBind.tv3.text = "压力最大值" + mBind.seekBar3.progress
                mBind.rightMaxET.setText("" + mBind.seekBar3.progress)
                val rightAxis: YAxis = mBind.chart.getAxisRight()
                rightAxis.axisMaximum = progress.toFloat()
                mBind.chart.notifyDataSetChanged()
                mBind.chart.invalidate()
            }

            mBind.seekBar4.id -> {
                Log.e("onProgressChanged", "操作右边最小值 " + progress)
                mmkv.putInt(ValueKey.SEEK_BAR_KEY_4, progress)
                mBind.tv4.text = "压力最小值" + mBind.seekBar4.progress
                mBind.rightMinET.setText("" + mBind.seekBar4.progress)
                val rightAxis: YAxis = mBind.chart.getAxisRight()
                rightAxis.axisMinimum = progress.toFloat()
                mBind.chart.notifyDataSetChanged()
                mBind.chart.invalidate()
            }
        }

    }

    override fun onStartTrackingTouch(seekBar: SeekBar?) {
    }

    override fun onStopTrackingTouch(seekBar: SeekBar?) {
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        Log.e("测试", "屏幕切换")
//        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//            setContentView(R.layout.activity_offline_data)
//        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
//            setContentView(R.layout.activity_offline_data)
//        }

    }

    override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
        super.onSaveInstanceState(outState, outPersistentState)
        Log.e("测试", "onSaveInstanceState")
    }

    override fun onRestoreInstanceState(
        savedInstanceState: Bundle?,
        persistentState: PersistableBundle?
    ) {
        super.onRestoreInstanceState(savedInstanceState, persistentState)
        Log.e("测试", "onRestoreInstanceState")
    }

    override fun onResume() {
        super.onResume()
    }
}